package com.wrh.draw.legend.test.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wrh.draw.bean.GridData;
import com.wrh.draw.util.ReadProGeoJson;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class ReadFile {


    public static GridData getTestRainGridData() {
        String filePath = "public/rainGrid.txt";
        InputStream dataStream = ReadFile.class.getClassLoader().getResourceAsStream(filePath);
        try {
            assert dataStream != null;
            String data = inputStreamToString(dataStream, StandardCharsets.UTF_8.toString());
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(data, GridData.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                assert dataStream != null;
                dataStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String inputStreamToString(InputStream inputStream, String charsetName) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        return result.toString(charsetName);
    }
}
